package com.xy.p2p.action.admin;



import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.image.ImageCaptchaService;
import com.xy.common.page.Pagination;
import com.xy.common.util.DictUtils;
import com.xy.common.security.BadCredentialsException;
import com.xy.common.security.UsernameNotFoundException;
import com.xy.common.security.encoder.PwdEncoder;
import com.xy.common.web.CookieUtils;
import com.xy.common.web.RequestUtils;
import com.xy.core.web.WebErrors;

import com.xy.p2p.model.Tfinanceinfo;
import com.xy.p2p.model.Timageinfo;
import com.xy.p2p.model.Tmember;
import com.xy.p2p.model.Tmemberassetaccount;
import com.xy.p2p.model.Tmemberassetaccountdetails;
import com.xy.p2p.model.Tmemberbadcredit;
import com.xy.p2p.model.Tmemberbankcard;
import com.xy.p2p.model.Tmembercredit;
import com.xy.p2p.model.Trecharge;
import com.xy.p2p.model.Ttenderrecord;
import com.xy.p2p.model.Ttransferinfo;
import com.xy.p2p.model.Ttransferrecord;
import com.xy.p2p.model.Twidrapp;
import com.xy.p2p.model.Tyedtransferout;
import com.xy.p2p.service.TfinanceinfoService;
import com.xy.p2p.service.TimageinfoService;
import com.xy.p2p.service.TmemberService;
import com.xy.p2p.service.TmemberassetaccountService;
import com.xy.p2p.service.TmemberassetaccountdetailsService;
import com.xy.p2p.service.TmemberbadcreditService;
import com.xy.p2p.service.TmemberbankcardService;
import com.xy.p2p.service.TmembercreditService;
import com.xy.p2p.service.TrechargeService;
import com.xy.p2p.service.TtenderrecordService;
import com.xy.p2p.service.TtransferinfoService;
import com.xy.p2p.service.TtransferrecordService;
import com.xy.p2p.service.TwidrappService;
import com.xy.p2p.service.TyedtransferoutService;



@Controller
public class TmemberAction{
	private static final Logger log = LoggerFactory.getLogger(TmemberAction.class);
	public TmemberAction() {
	}
 
 
 	/**
	 * 会员信息新增页面
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_tmemberAdd.do")
	public String add(HttpServletRequest request, ModelMap model) {
		model.addAttribute("tmember", new Tmember());
        setDict(model);
		return "tmemberEdit";
	}

	/**
	 * 会员信息新增保存
	 * 
	 * @param tmember
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/o_tmemberSave.do")
	public String save(Tmember tmember, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateSave(tmember, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		tmember = tmemberService.save(tmember);
		return "redirect:v_tmemberList.do";
	}

	/**
	 * 会员信息删除
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping("o_tmemberDelete.do")
	public String delete(long[] ids) {
		if (ids != null) {
			for (long id : ids) {
				tmemberService.remove(id);
			}
		}
		return "redirect:v_tmemberList.do";
	}

	/**
	 * 会员信息编辑页面
	 * 
	 * @param memberid
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_tmemberEdit.do")
	public String edit(long memberid, HttpServletRequest request, ModelMap model) {
		Tmember tmember = tmemberService.get(memberid);
		model.addAttribute("tmember", tmember);
        setDict(model);
		return "tmemberEdit";
	}

	/**
	 * 会员信息详情
	 * 
	 * @param memberid
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_tmemberDetail.do")
	public String detail(long memberid, HttpServletRequest request, ModelMap model) {
		Tmember tmember = tmemberService.get(memberid);
		model.addAttribute("tmember", tmember);
        setDict(model);
		return "tmemberView";
	}
	/**
	 * 密码重置
	 * 
	 * */
	@RequestMapping("v_reset.do")
	public String reset2(Tmember tmember){
		String str = "123456";
		tmember.setPasswd(pwdEncoder.encodePassword(str));
		tmemberService.save(tmember);
		return "text";
	}
	/**
	 * 提现密码重置
	 * 
	 * */
	@RequestMapping("v_resetwithdrawpassword.do")
	public String resetwithdrawpassword(Tmember tmember){
		String str = "123456";
		tmember.setWithdrawpassword(pwdEncoder.encodePassword(str));
		tmemberService.save(tmember);
		return "text";
	}
	/**
	 * 会员信息查询（分页）
	 * 
	 * @param tmember
	 * @param pageNo
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_tmemberList.do")
	public String listPage(Tmember tmember, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		if (pageNo == null)
			pageNo = 1;
		Pagination pagination = tmemberService.getTmemberByPage(toMap(tmember),
				pageNo, CookieUtils.getPageSize(request));
		model.addAttribute("pagination", pagination);
        setDict(model);
		return "tmemberList";
	}

	/**
	 * 会员信息查询
	 * 
	 * @param tmember
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_tmemberList1.do")
	public String list(Tmember tmember, HttpServletRequest request, ModelMap model) {
		List<Tmember> list = tmemberService.getTmember(toMap(tmember));
		model.addAttribute("list", list);
        setDict(model);
		return "tmemberList";
	}
	/*
	 * 查询
	 * */
	@RequestMapping("v_tmemberList2.do")
	public String list2(Tmember tmember, Integer pageNo, HttpServletRequest request, ModelMap model) {
		if (pageNo == null)
			pageNo = 1;
		Pagination pagination = tmemberService.getTmemberByPage(toMap(tmember), pageNo, CookieUtils.getPageSize(request));
		model.addAttribute("pagination", pagination);
		setDict(model);
		return "tmemberInfo";
		}
	/*
	 * 详细查询
	 * */
	
	@RequestMapping("v_tmemberList3.do")
	public String list3(Integer pageNo,String idname,long id,HttpServletRequest request, ModelMap model) {
		if (pageNo == null)
			pageNo = 1;
		if(null == idname)
			idname = "0";
		model.addAttribute("idname",idname);
		Tmember tmember = new Tmember();
		//取当前点击的用户id
		tmember.setMemberid(id);
		//列出当前用户的个人信息
		List<Tmember> list= tmemberService.getTmember(toMap(tmember));
		model.addAttribute("entity", list.get(0));
		//设置其他表的memberid字段
		Map<String,Object> map2=new HashMap<String, Object>();
		map2.put("Tmember", tmember);
		//列出当前用户的资产账户信息
		List<Tmemberassetaccount> list2 = tmemberassetaccountService.getTmemberassetaccount(map2);
		model.addAttribute("list2",list2);
		//列出当前用户的银行卡信息
		List<Tmemberbankcard> list3 = tmemberbankcardService.getTmemberbankcard(map2);
		model.addAttribute("list3", list3);
		//列出当前用户的资产账户交易明细
//		List<Tmemberassetaccountdetails> list4 = tmemberassetaccountdetailsService.getTmemberassetaccountdetails(map2);
		Pagination pagination4 = tmemberassetaccountdetailsService.getTmemberassetaccountdetailsByPage(map2,
				pageNo, CookieUtils.getPageSize(request));
		for (Object t : pagination4.getList()) {
			if(this.tryPaseLong(((Tmemberassetaccountdetails)t).getOtherside())){
				((Tmemberassetaccountdetails)t).setTfinanceinfo(tfinanceinfoService.get(Long.parseLong(((Tmemberassetaccountdetails)t).getOtherside())));
			}
		}
		model.addAttribute("pagination4",pagination4);
		//列出当前用户的信用信息
		List<Tmembercredit> list5 = tmembercreditService.getTmembercredit(map2);
		model.addAttribute("list5",list5);
		//列出当前用户的不良信用记录
		List<Tmemberbadcredit> list6 = tmemberbadcreditService.getTmemberbadcredit(map2);
	    model.addAttribute("list6",list6);
		//列出当前用户的融资标的信息
//		List<Tfinanceinfo> list7 = tfinanceinfoService.getTfinanceinfo(map2);
	    Pagination pagination7 = tfinanceinfoService.getTfinanceinfoByPage(map2, pageNo, CookieUtils.getPageSize(request));
		model.addAttribute("pagination7",pagination7);
		//列出当前用户的投标记录
//		List<Ttenderrecord> list8 = ttenderrecordService.getTtenderrecord(map2);
		Pagination pagination8 = ttenderrecordService.getTtenderrecordByPage(map2, pageNo, CookieUtils.getPageSize(request));
		model.addAttribute("pagination8",pagination8);
		//列出当前用户的转让标的信息
//		List<Ttransferinfo> list9 = ttransferinfoService.getTtransferinfo(map2);
		Pagination pagination9 = ttransferinfoService.getTtransferinfoByPage(map2, pageNo, CookieUtils.getPageSize(request));
		model.addAttribute("pagination9",pagination9);
		//列出当前用户的提现申请信息
//		List<Twidrapp> list10 = twidrappService.getTwidrapp(map2);
		Pagination pagination10 = twidrappService.getTwidrappByPage(map2, pageNo, CookieUtils.getPageSize(request));
		model.addAttribute("pagination10",pagination10);
		//余额贷转出记录
//		List<Tyedtransferout> list11 = tyedtransferoutService.getTyedtransferout(map2);
		Pagination pagination11 = tyedtransferoutService.getTyedtransferoutByPage(map2, pageNo, CookieUtils.getPageSize(request));
		model.addAttribute("pagination11",pagination11);
		//充值记录
		Map<String, Object> RCMap = new HashMap<String, Object>();
		RCMap.put("memberid", tmember.getMemberid());
		RCMap.put("status", "01");
		List<Trecharge> list12 = trechargeService.getTrecharge(RCMap);
		model.addAttribute("list12", list12);
		model.addAttribute("timageinfos",timageinfoService.getTimageinfo(map2));
        setDict(model);
		return "tmemberInfoExpatiation";
	}
	
	private boolean tryPaseLong(String prarm){
		try {
			Long.parseLong(prarm);
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	
 	/***
	 * 将页面输入信息转成map
	 * 
	 * @param tmember
	 * @return
	 */	private Map<String,Object> toMap(Tmember tmember){
		Map<String,Object> map=new HashMap<String, Object>();
      		if(tmember.getMemberid()!=null&&!tmember.getMemberid().equals("")){
			map.put("memberid", tmember.getMemberid());
		}
		if(tmember.getLoginname()!=null&&!tmember.getLoginname().equals("")){
			map.put("loginname", tmember.getLoginname());
		}
		if(tmember.getPasswd()!=null&&!tmember.getPasswd().equals("")){
			map.put("passwd", tmember.getPasswd());
		}
		if(tmember.getUsertype()!=null&&!tmember.getUsertype().equals("")){
			map.put("usertype", tmember.getUsertype());
		}
		if(tmember.getTruename()!=null&&!tmember.getTruename().equals("")){
			map.put("truename", tmember.getTruename());
		}
		if(tmember.getSex()!=null&&!tmember.getSex().equals("")){
			map.put("sex", tmember.getSex());
		}
		if(tmember.getIdcard()!=null&&!tmember.getIdcard().equals("")){
			map.put("idcard", tmember.getIdcard());
		}
		if(tmember.getBirthday()!=null&&!tmember.getBirthday().equals("")){
			map.put("birthday", tmember.getBirthday());
		}
		if(tmember.getPhone()!=null&&!tmember.getPhone().equals("")){
			map.put("phone", tmember.getPhone());
		}
		if(tmember.getEmail()!=null&&!tmember.getEmail().equals("")){
			map.put("email", tmember.getEmail());
		}
		if(tmember.getEdudegree()!=null&&!tmember.getEdudegree().equals("")){
			map.put("edudegree", tmember.getEdudegree());
		}
		if(tmember.getGraduated()!=null&&!tmember.getGraduated().equals("")){
			map.put("graduated", tmember.getGraduated());
		}
		if(tmember.getMarriage()!=null&&!tmember.getMarriage().equals("")){
			map.put("marriage", tmember.getMarriage());
		}
		if(tmember.getAddr()!=null&&!tmember.getAddr().equals("")){
			map.put("addr", tmember.getAddr());
		}
		if(tmember.getWorktype()!=null&&!tmember.getWorktype().equals("")){
			map.put("worktype", tmember.getWorktype());
		}
		if(tmember.getCorpindustry()!=null&&!tmember.getCorpindustry().equals("")){
			map.put("corpindustry", tmember.getCorpindustry());
		}
		if(tmember.getCorpsize()!=null&&!tmember.getCorpsize().equals("")){
			map.put("corpsize", tmember.getCorpsize());
		}
		if(tmember.getPosition()!=null&&!tmember.getPosition().equals("")){
			map.put("position", tmember.getPosition());
		}
		if(tmember.getIncome()!=null&&!tmember.getIncome().equals("")){
			map.put("income", tmember.getIncome());
		}
		if(tmember.getRegtime()!=null&&!tmember.getRegtime().equals("")){
			map.put("regtime", tmember.getRegtime());
		}
		if(tmember.getModtime()!=null&&!tmember.getModtime().equals("")){
			map.put("modtime", tmember.getModtime());
		}
		if(tmember.getRegip()!=null&&!tmember.getRegip().equals("")){
			map.put("regip", tmember.getRegip());
		}
		if(tmember.getLogtimes()!=null&&!tmember.getLogtimes().equals("")){
			map.put("logtimes", tmember.getLogtimes());
		}
		if(tmember.getErrtimes()!=null&&!tmember.getErrtimes().equals("")){
			map.put("errtimes", tmember.getErrtimes());
		}
		if(tmember.getLastloginip()!=null&&!tmember.getLastloginip().equals("")){
			map.put("lastloginip", tmember.getLastloginip());
		}
		if(tmember.getLastlogintime()!=null&&!tmember.getLastlogintime().equals("")){
			map.put("lastlogintime", tmember.getLastlogintime());
		}
		if(tmember.getActivationcode()!=null&&!tmember.getActivationcode().equals("")){
			map.put("activationcode", tmember.getActivationcode());
		}
		if(tmember.getStatus()!=null&&!tmember.getStatus().equals("")){
			map.put("status", tmember.getStatus());
		}      
		if (tmember.getEmailstatus() != null && !tmember.getEmailstatus().equals("")){
			map.put("emailstatus", tmember.getEmailstatus());
		}
		
		return map;
	}
   
	/**
	 * 设置页面所需的数据字典
	 * @param model
	 */
	private void setDict(ModelMap model){
	  //会员个人信息数据字典
      model.addAttribute("usertypeMap", DictUtils.getDictByType(DictUtils.TMEMBER_USERTYPE));
      model.addAttribute("sexMap", DictUtils.getDictByType(DictUtils.TMEMBER_SEX));
      model.addAttribute("edudegreeMap", DictUtils.getDictByType(DictUtils.TMEMBER_EDUDEGREE));
      model.addAttribute("marriageMap", DictUtils.getDictByType(DictUtils.TMEMBER_MARRIAGE));
      model.addAttribute("worktypeMap", DictUtils.getDictByType(DictUtils.TMEMBER_WORKTYPE));
      model.addAttribute("tmemberstatusMap", DictUtils.getDictByType(DictUtils.TMEMBER_STATUS));
      model.addAttribute("cbcreditMap", DictUtils.getDictByType(DictUtils.TMEMBER_CBCREDIT));
      model.addAttribute("fixedassetsMap", DictUtils.getDictByType(DictUtils.TMEMBER_FIXEDASSETS));
      model.addAttribute("currentassetsMap", DictUtils.getDictByType(DictUtils.TMEMBER_CURRENTASSETS));
      model.addAttribute("corpsizeMap", DictUtils.getDictByType(DictUtils.TMEMBER_CORPSIZE));
      model.addAttribute("emailstatusMap",DictUtils.getDictByType(DictUtils.TMEMBER_EMAILSTATUS));
      //资产账户信息数据字典
      model.addAttribute("statusMap", DictUtils.getDictByType(DictUtils.TMEMBERASSETACCOUNT_STATUS));
      //资产账户交易明细数据字典
      model.addAttribute("borrowingMap", DictUtils.getDictByType(DictUtils.TMEMBERASSETACCOUNTDETAILS_BORROWING));
      model.addAttribute("trantypeMap", DictUtils.getDictByType(DictUtils.TMEMBERASSETACCOUNTDETAILS_TRANTYPE));
      //不良信用记录数据字典
      model.addAttribute("badcreditlevelMap", DictUtils.getDictByType(DictUtils.TMEMBERBADCREDIT_BADCREDITLEVEL));
      model.addAttribute("badcreditstatusMap", DictUtils.getDictByType(DictUtils.TMEMBERBADCREDIT_STATUS));
      //融资标的信息数据字典
      model.addAttribute("repaymentperiodMap", DictUtils.getDictByType(DictUtils.TFINANCEINFO_REPAYMENTPERIOD));
      model.addAttribute("repaymentmodMap", DictUtils.getDictByType(DictUtils.TFINANCEINFO_REPAYMENTMOD));
      model.addAttribute("repaymentstatusMap", DictUtils.getDictByType(DictUtils.TFINANCEINFO_STATUS));
      //投标记录数据字典
      model.addAttribute("istransferMap", DictUtils.getDictByType(DictUtils.TTENDERRECORD_ISTRANSFER));
      //转让标的信息数据字典
      model.addAttribute("ttransferinfostatusMap", DictUtils.getDictByType(DictUtils.TTRANSFERINFO_STATUS));
      model.addAttribute("istransferMap", DictUtils.getDictByType(DictUtils.TTRANSFERINFO_ISTRANSFER));	
      //提现申请数据字典
      model.addAttribute("twidrappstatusMap", DictUtils.getDictByType(DictUtils.TWIDRAPP_STATUS));
      //充值记录
      model.addAttribute("rcstatusMap", DictUtils.getDictByType(DictUtils.TRECHARGE_STATUS));
      //用户资料上传字典
      model.addAttribute("tistatusMap", DictUtils.getDictByType(DictUtils.TIMAGEINFO_STATUS));
	}

	/**
	 * 数据校验
	 * @param model
	 */
	private WebErrors validateSave(Tmember tmember, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		/**if (errors.ifOutOfLength(username, "username", 1, 100)) {
			return errors;
		}  */    
		return errors;
	}


	/**
	 * 检查登陆名是否已经存在
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/check_loginname.do")
	public void check_loginname(ModelMap model, HttpServletRequest request,HttpServletResponse response)
			throws Exception {
      try{
		String loginname=request.getParameter("loginname");
		if(loginname==null||loginname.equals("")){
			response.getWriter().write("false");
			return;
		}
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("loginname", loginname);
		List l = tmemberService.getTmember(param);
		String text=l.size()==0?"true":"false";         
  		response.setContentType("text/xml;charset=UTF-8");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.getWriter().write(text);
      } catch (Exception e) {
			log.error(e.toString());
         throw e;
		}
      
	}   
      
	@Resource
	private TmemberService tmemberService;
	@Resource
	private TmemberbankcardService tmemberbankcardService;
	@Resource
	private TmemberassetaccountService tmemberassetaccountService; 
	@Resource
	private TmemberassetaccountdetailsService tmemberassetaccountdetailsService;
	@Resource
	private TmembercreditService tmembercreditService;
	@Resource
	private TmemberbadcreditService tmemberbadcreditService;
	@Resource
	private TfinanceinfoService tfinanceinfoService;
	@Resource
	private TtenderrecordService ttenderrecordService;
	@Resource
	private TtransferinfoService ttransferinfoService;
	@Resource
	private TwidrappService twidrappService;
	@Resource
	private TtransferrecordService ttransferrecordService;
	@Resource
	private TyedtransferoutService tyedtransferoutService;
	@Resource
	private TrechargeService trechargeService;
	@Resource
	private PwdEncoder pwdEncoder;
	@Resource
	private TimageinfoService timageinfoService;
}